<?php namespace App\Api\Http\ApiControllers;

use App\Exceptions\OtherException;
use App\Api\Http\Requests\ProjectRequest;
use App\Repositories\Eloquent\Item\Entity\ProjectEntity;
use App\Repositories\Item\ProjectRepositoryInterface;
use Illuminate\Http\Request;

class PublisherProjectController extends Controller
{
    /**
     * @var ProjectRepositoryInterface
     */
    protected $project_repository;

    public function __construct(ProjectRepositoryInterface $project_repository)
    {
        $this->project_repository = $project_repository;
    }

    public function show($id)
    {
        $item = $this->project_repository->show((int)$id);
        throw_unless($item, new OtherException('项目不存在'));

        throw_if($item->creator_uid != access()->id(), new OtherException('没有权限查看'));

        $item->load('contact');

        return response()->json($item->toArray());
    }

    public function store(ProjectRequest $request)
    {
        $entity = $this->createProjectEntity($request);

        $model = $this->project_repository->store($entity);
        $project = $model->only(['id', 'name']);
        if ($model->contact) {
            $project['contact'] = $model->contact->only(['name', 'phone']);
        }

        return response()->json($project, 201);
    }

    public function update($id, ProjectRequest $request)
    {
        $entity = $this->createProjectEntity($request);

        $this->project_repository->update($id, $entity);

        return response('', 204);
    }

    private function createProjectEntity(Request $request)
    {
        $entity = new ProjectEntity();
        $entity->creator_uid = access()->id();
        $entity->name = $request->get('name');
        $entity->contact_name = $request->get('contact_name');
        $entity->contact_phone = $request->get('contact_phone');

        return $entity;
    }
}
